package com.sws.hm.crontab;


import com.sws.hm.dao.portDao;
import com.sws.hm.dto.port;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.ConnectException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Component
public class crontabSocket {
    @Autowired
    portDao dao;

    @Scheduled(cron="${port.schedule}")
    public  void AnimalAechartsMapper() throws IOException, ParseException {
        java.net.Socket client = null;
        String search=null;
        List<port> list=dao.findAll(search);
        for (int j=0;j<list.size();j++){

            String id=list.get(j).getId();
            String ip=list.get(j).getIp();
            String mc=list.get(j).getMc();
            String prot=list.get(j).getProt();
            int protInt=Integer.parseInt(prot);
            try{
                client = new java.net.Socket(ip, protInt);
                System.out.println("连接已建立...");
                client.close();
                Date time=getDate();
                dao.updateSocket(id,mc,ip,prot,"0",time);

            }  catch(ConnectException e) {
                System.out.println("未建立连接！！！");

                Date time=getDate();
                dao.updateLixianSocket(id,mc,ip,prot,"1");


            }
        }

    }

    public Date getDate() throws ParseException {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar calendar = Calendar.getInstance();
        String dateName = df.format(calendar.getTime());
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = sf.parse(dateName);
        return  date;
    }


}
